<?php
namespace app\api\controller\newfile;

use think\Request;
use app\common\model\newmodel\Customer as CustomerModel;
use app\common\model\power\Rolepower;
use app\common\model\newmodel\User as UserModel;
use app\common\model\newmodel\UserAgency;
use app\common\model\customer\Customer as CustomermodelOne;
use app\common\model\newmodel\Contract as ContractModel;

use app\api\controller\Pub;
use app\api\controller\Base;

class Customer extends Base
{
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(401001);
	}

    /**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}

    public function getcreateinitinfo()
    {
        $data['StateList'] = CustomermodelOne::getStatusText();
        $data['ScaleList'] = array_del_empty(CustomermodelOne::distinct(true)->column('Scale'));
        $data['TypeList'] = array_del_empty(CustomermodelOne::distinct(true)->column('Type'));
        return myok($data);
    }

    //搜索获取单个客户的详细信息找到对应的客户添加合同提供customer_id;
    public function customerDetail()
    {
        $userId=Pub::userid();
        $user =UserModel::get($userId);
        $role= $user->Role;
        
        $data=input();
        $companyName=$data['companyName'] ?? '';
        if(empty($companyName)){
            return json([
                'code' =>false,
                'msg'  =>'请输入企业名称'
            ]); 
        }

        if($role==201){
            $res=CustomerModel::where('Name','like',"%$companyName%")->where('LatestAgentId',0)->select()->toArray();
        }elseif($role==401){
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            $agencyIds = UserAgency::getUserIdsByAgencyId($agencyId);
            $res=CustomerModel::where('Name','like',"%$companyName%")->whereIn('LatestAgentId',$agencyIds)->select()->toArray();
        }elseif($role==402){
            $res=CustomerModel::where('Name','like',"%$companyName%")->where('LatestAgentId',$userId)->select()->toArray();
        }
        
        return myok($res);
    }

    /**
     * 获取客户列表
     */
    public function customerList()
    {
        $data=input();
        $page = $data['page'] ?? 1;
        $pageSize = $data['pageSize'] ?? 10;
        $keyword = $data['keyword'] ?? '';
        $state = $data['state'] ?? 1;
        $userId = Pub::userid();
        $result = CustomerModel::getCustomerList($state,$userId, $page, $pageSize, $keyword);
        
        return json($result);
    }

    public function customerInfo()
    {
        $customer_id=input('CustomerId');
        if(!$customer_id){
            return json(['code' => false, 'msg' => '客户id不能为空']);
        }
        $customer=CustomerModel::where('CustomerId',$customer_id)->find();
        $contractData=ContractModel::where('customer_id',$customer_id)->select()->toArray();
        $customer['contractData']=$contractData;
        return  json(['code' => true, 'data' =>$customer]);
    }

    /**
     * 添加客户
     */
    public function customerAdd()
    {
        $data = input('post.');
        if (empty($data['UserName']) || empty($data['Tel'])) {
            return json(['code' => false, 'msg' => '客户名称和电话不能为空']);
        }
        
        $userId = Pub::userid();
        $userInfo = UserModel::get($userId);
        $role = $userInfo->Role;
        
        // 根据角色设置代理商信息
        if ($role == 401 || $role == 402) {
            // 代理商管理员或员工 - 设置代理商ID
                $data['LatestAgentId'] = $userId;
                $data['IsAgent'] = 0;
        } elseif($role == 201) {
            // 业务员 - 设置为非代理商
            $data['IsAgent'] = 0;
            $data['LatestAgentId'] = null;
            $data['BussinessId']=$userId;
        }
        $result = CustomerModel::addCustomer($data);
        return json($result);
    }

    /**
     * 编辑客户信息
     */
    public function customerEdit()
    {
        $data = input('post.');
        if (empty($data['CustomerId']) || empty($data['UserName']) || empty($data['Tel'])) {
            return json(['code' => false, 'msg' => '客户ID、名称和电话不能为空']);
        }
        
        $result = CustomerModel::editCustomer($data);
        return json($result);
    }

    /**
     * 删除客户
     */
    public function customerDel()
    {
        $CustomerId = input('CustomerId');
        if (empty($CustomerId)) {
            return json(['code'=>false, 'msg'=>'参数不完整']);
        }
        $customer=CustomerModel::get($CustomerId);
        if(!$customer){
            return json(['code'=>false, 'msg'=>'客户不存在']);
        }
        $customer->State=3;
        $customer->save();
        return json(['code'=>true, 'msg'=>'删除成功']);
    }

    //代理商管理员将客户分给制定的代理商员工(代理商管理员权限)
    public function customerChangeAgency()
    {   
        $data=input('post.');
       
        if(empty($data['user_id']) || empty($data['customer_id'])){
            return json(['code'=>false, 'msg'=>'参数不完整']);
        }
        $user_id=$data['user_id'];
        $customer_id=$data['customer_id'];
        CustomerModel::ChangeAgency($user_id,$customer_id);
        return json(['code'=>true, 'msg'=>'分配成功']);
    }
}
